using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Input.Platform;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using System.Collections.Specialized;
using Avalonia.Platform.Storage;
using System.IO;
using DesktopApp.Views;
using DesktopApp.Models;
using DesktopApp.ViewModels.Services;
using System.Text.Json;
using CommunityToolkit.Mvvm.Input;
using Avalonia.Styling;
using Avalonia.Media;

namespace DesktopApp.ViewModels
{
    // Helper record for grouping
    // public record RuleGroup(string GroupName, IEnumerable<RuleItemViewModel> Items); // Moved to RulesViewModel

    public class MainWindowViewModel : ViewModelBase // Will become the ShellViewModel
    {
        // --- Theme Selection Properties ---
        public ObservableCollection<string> AvailableThemes { get; } = new ObservableCollection<string> { "跟随系统", "Light", "Dark" };

        private string _selectedTheme = "跟随系统"; // Default to Follow System theme
        public string SelectedTheme
        {
            get => _selectedTheme;
            set
            {
                Debug.WriteLine($"[MainWindowViewModel] SelectedTheme setter called with value: {value}");
                if (SetProperty(ref _selectedTheme, value))
                {
                    Debug.WriteLine("[MainWindowViewModel] SelectedTheme property changed. Applying theme.");
                    ApplyTheme(value);
                }
                else
                {
                    Debug.WriteLine("[MainWindowViewModel] SelectedTheme value did not change.");
                }
            }
        }

        // Add WindowTitle property
        public string WindowTitle => "日志简化小助手"; // Simple read-only property

        // --- Private Fields ---
        // Keep services needed by ShellViewModel or its remaining direct responsibilities
        private readonly ILogFileService _logFileService; // Needed for LogPanelViewModel
        private readonly IRuleManagementService _ruleManagementService; // Needed for RulesViewModel
        private readonly ILogProcessingService _logProcessingService; // Needed for StatusBarViewModel
        private readonly IUIService _uiService; // Needed for Shell, Rules, LogPanel, StatusBar
        private readonly IStatisticsService _statisticsService; // Needed for StatusBarViewModel

        // --- Child ViewModels ---
        public RulesViewModel RulesVm { get; }
        public LogPanelViewModel LogPanelVm { get; }
        public StatusBarViewModel StatusBarVm { get; }


        // --- Properties Moved to Child ViewModels ---
        // public ObservableCollection<RuleItemViewModel> Rules { get; } = new ObservableCollection<RuleItemViewModel>(); // Moved to RulesViewModel
        // public ObservableCollection<LogProcessingTemplate> Templates { get; } = new ObservableCollection<LogProcessingTemplate>(); // Moved to RulesViewModel
        // private string _originalLogText = string.Empty; // Moved to LogPanelViewModel
        // public string OriginalLogText { ... } // Moved to LogPanelViewModel
        // private string _resultLogText = string.Empty; // Moved to LogPanelViewModel
        // public string ResultLogText { ... } // Moved to LogPanelViewModel
        // --- Statistics Properties --- // Moved to StatusBarViewModel
        // private int _originalLineCount = 0;
        // public int OriginalLineCount { ... }
        // private int _resultLineCount = 0;
        // public int ResultLineCount { ... }
        // private string _reductionRateText = "精简率: N/A";
        // public string ReductionRateText { ... }
        // private string _ruleStatsText = "启用: 0 / 总计: 0";
        // public string RuleStatsText { ... }
        // private string _appliedRulesSummary = "已应用: 无";
        // public string AppliedRulesSummary { ... }
        // private string _currentTemplateLabel = "通用日志 (默认)"; // Moved to RulesViewModel/StatusBarViewModel? Let's keep in RulesVM for now
        // public string CurrentTemplateLabel { ... }
        // private RuleItemViewModel? _selectedRule; // Moved to RulesViewModel
        // public RuleItemViewModel? SelectedRule { ... }
        // private LogProcessingTemplate? _selectedTemplate; // Moved to RulesViewModel
        // public LogProcessingTemplate? SelectedTemplate { ... }
        // private string? _selectedOriginalLogText; // Moved to LogPanelViewModel
        // public string? SelectedOriginalLogText { ... }

        // --- Commands Moved to Child ViewModels ---
        // public ICommand EditRuleCommand { get; } // RulesViewModel
        // public ICommand DeleteRuleCommand { get; } // RulesViewModel
        // public ICommand AddRuleCommand { get; } // RulesViewModel
        // public ICommand SaveTemplateCommand { get; } // RulesViewModel
        // public ICommand DeleteTemplateCommand { get; } // RulesViewModel
        // public ICommand ProcessCommand { get; } // StatusBarViewModel
        // public ICommand CopyResultCommand { get; } // LogPanelViewModel
        // public ICommand ClearLogsCommand { get; } // LogPanelViewModel
        // public ICommand PasteLogCommand { get; } // LogPanelViewModel
        // public ICommand OpenLogCommand { get; } // LogPanelViewModel
        // public ICommand SaveResultCommand { get; } // LogPanelViewModel
        // public ICommand CreateRuleFromSelectionCommand { get; } // RulesViewModel


        // --- Commands Remaining in ShellViewModel ---
        public ICommand ShowAboutCommand { get; }
        public ICommand SubmitFeedbackCommand { get; }

        // --- Grouped Rules for UI --- // Moved to RulesViewModel
        // public IEnumerable<RuleGroup> GroupedRules => GenerateGroupedRules();

        public MainWindowViewModel(ILogFileService logFileService, 
                                 IRuleManagementService ruleManagementService,
                                 ILogProcessingService logProcessingService,
                                 IUIService uiService,
                                 IStatisticsService statisticsService)
        {
            _logFileService = logFileService;
            _ruleManagementService = ruleManagementService;
            _logProcessingService = logProcessingService;
            _uiService = uiService;
            _statisticsService = statisticsService;

            // --- Create Child ViewModels ---
            // Order matters if VMs depend on each other during construction
            LogPanelVm = new LogPanelViewModel(logFileService /*, uiService */);
            // RulesVm needs LogPanelVm
            RulesVm = new RulesViewModel(ruleManagementService, uiService, LogPanelVm); 
            // StatusBarVm needs references to the other VMs
            StatusBarVm = new StatusBarViewModel(logProcessingService, statisticsService, uiService, RulesVm, LogPanelVm);

            // --- Initialize ShellViewModel Commands ---
            ShowAboutCommand = new AsyncRelayCommand(ShowAboutDialog);
            SubmitFeedbackCommand = new AsyncRelayCommand(SubmitFeedback);

            // --- Setup Coordination (Example: Update stats when rules change) ---
             // RulesVm.RulesChangedForStats += (sender, args) => StatusBarVm?.RecalculateRuleStatistics(); // Add when StatusBarVm exists

            // Apply initial theme based on SelectedTheme (remains here)
            ApplyTheme(SelectedTheme);

            // Initial data loading is now handled within RulesViewModel constructor
            // _ = LoadInitialDataAsync(); // Moved to RulesViewModel
        }


        // --- Event Handlers for Rule Stats --- // Moved to RulesViewModel
        // private void Rules_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { ... }
        // private void Rule_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { ... }

        // --- Statistics Update Methods --- // Moved to StatusBarViewModel
        // private void RecalculateRuleStatistics() { ... }
        // private void RecalculateLogStatistics() { ... }

        // --- Command Execution Methods (Moved) ---
        // private async Task ProcessLogs() { ... } // StatusBarViewModel
        // private async void CopyResultToClipboard() { ... } // LogPanelViewModel
        // private bool CanCopyResultToClipboard() { ... } // LogPanelViewModel
        // private void ClearLogs(object? parameter) { ... } // LogPanelViewModel
        // private bool CanClearLogs(object? parameter) { ... } // LogPanelViewModel
        // private async void PasteLog() { ... } // LogPanelViewModel
        // private bool CanPasteLog() { ... } // LogPanelViewModel
        // private async void OpenLog() { ... } // LogPanelViewModel
        // private async void SaveResult() { ... } // LogPanelViewModel
        // private bool CanSaveResult() { ... } // LogPanelViewModel
        // private async void AddRule() { ... } // RulesViewModel
        // private async void EditRule(object? parameter) { ... } // RulesViewModel
        // private async void DeleteRule(object? parameter) { ... } // RulesViewModel
        // private bool CanEditOrDeleteRule(object? parameter) { ... } // RulesViewModel
        // public void MoveRule(RuleItemViewModel sourceRule, RuleItemViewModel? targetRule, bool dropBefore) { ... } // RulesViewModel


        // --- Template Management Logic (Moved) ---
        // private async Task LoadInitialDataAsync() { ... } // RulesViewModel
        // private void LoadDefaultRules() { ... } // RulesViewModel (Helper inside LoadInitialDataAsync/LoadTemplateAsync)
        // private async Task DeleteSelectedTemplate(object? parameter) { ... } // RulesViewModel
        // private bool CanDeleteTemplate(object? parameter) { ... } // RulesViewModel
        // private async Task SaveCurrentRulesAsTemplate() { ... } // RulesViewModel
        // private async void LoadTemplate(LogProcessingTemplate? template) { ... } // RulesViewModel (Triggered by SelectedTemplate setter)

        // --- About Dialog Logic (Remains/Uses Service) ---
        private async Task ShowAboutDialog()
        {
            Debug.WriteLine("ShowAbout command executed via UI Service");
            await _uiService.ShowAboutDialogAsync(); // Correct: delegates to service
        }

        // --- Rule Creation from Selection Logic (Moved) ---
        // private async Task CreateRuleFromSelection(string? selection) { ... } // RulesViewModel

        // --- Theme Application Logic (Remains/Uses Service) ---
        private void ApplyTheme(string? themeName)
        {
            Debug.WriteLine($"ShellViewModel: Applying theme: {themeName}");
            ThemeVariant themeVariant;
            switch (themeName)
            {
                case "Dark": themeVariant = ThemeVariant.Dark; break;
                case "跟随系统": themeVariant = ThemeVariant.Default; break; // Use Default for system theme
                case "Light": default: themeVariant = ThemeVariant.Light; break;
            }
            // Call UIService to apply the theme
             _uiService.ApplyTheme(themeVariant); // Correct: delegates to service
        }

        // --- Grouped Rules for UI (Moved) ---
        // private IEnumerable<RuleGroup> GenerateGroupedRules() { ... } // RulesViewModel
        // private string GetRuleTypeDisplayName(RuleType type) { ... } // RulesViewModel
        // private int GetRuleTypeSortOrder(RuleType type) { ... } // RulesViewModel

        // --- Submit Feedback Logic (Remains/Uses Service) ---
        private Task SubmitFeedback()
        {
            Debug.WriteLine("SubmitFeedback command executed.");
            // await _uiService.OpenFeedbackAsync(); // Removed: OpenFeedbackAsync missing
            // Implement feedback mechanism using Process.Start
            string feedbackUrl = "https://gitee.com/luoyaosheng/log-clear/issues"; // Your feedback URL
            try
            {
                Process.Start(new ProcessStartInfo(feedbackUrl) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to open feedback URL: {ex.Message}");
                // Optionally: Use _uiService to show an error message if ShowMessageAsync exists
                // await _uiService.ShowMessageAsync("错误", $"无法打开反馈链接: {ex.Message}");
            }
            return Task.CompletedTask;
        }

        // AssignCommandsToRule - Moved/Removed
        // private void AssignCommandsToRule(RuleItemViewModel rule) { ... }
    }
} 